// ==UserScript==
// @name         Discogs: Label Pack Collector
// @namespace    labelpackcollector.user.js
// @version      0.1
// @match        https://www.discogs.com/label/*
// @run-at       document-end
// ==/UserScript==

(async () => {
	'use strict';

	const {pathname: currentLabel} = new URL(location);

	const releases = document.querySelectorAll('.card.r_tr');
	for await (const element of releases) {
		const {className, cells, children, dataset: {objectType, objectId, shadowcat}} = element;
		const {firstElementChild: {firstElementChild}} = cells[10];
		if (className.includes('card_in_wantlist')) {
			const {nextElementSibling} = firstElementChild;
			try {
				const {status} = await fetch('https://www.discogs.com/_rest/wantlist/' + objectId, {method: 'DELETE'});
				if (status === 204) {
					nextElementSibling.style.display = 'none';
					nextElementSibling.innerHTML = '';
				} else {
					nextElementSibling.style.display = 'block';
					nextElementSibling.style.background = '#BF3A38';
					nextElementSibling.innerHTML = 'Error: Wantlist';
				}
			} catch (error) {
				console.log(error);
			}
		}

		if (className.includes('card_in_collection') || objectType !== 'release') {
			continue;
		}

		const {href} = children[5].children[0];
		const {pathname} = new URL(href);
		if (pathname !== currentLabel) {
			continue;
		}

		const {textContent} = children[4].children[1];
		if (/CD|Vinyl/g.test(textContent)) {
			continue;
		}

		const data = {release_id: objectId, shadowcat};
		try {
			const {status} = await fetch('https://www.discogs.com/_rest/collection', {method: 'POST', body: JSON.stringify(data), headers: {'Content-Type': 'application/json'}});
			if (status === 200) {
				firstElementChild.removeAttribute('style');
				firstElementChild.innerHTML = 1;
			} else {
				firstElementChild.style.display = 'block';
				firstElementChild.style.background = '#BF3A38';
				firstElementChild.innerHTML = 'Error: Collection';
			}
		} catch (error) {
			console.log(error);
		}
	}
})();
